name: ci

on:
  push:
    branches:
      - main

jobs:
  build-docs:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - uses: actions/setup-python@v2
        with:
          python-version: 3.8

      - name: build docs
        run: | 
          echo "-------- install requirements for docs --------"
          pip install -r requirements.txt
          cd docs
          pip install -r requirements.txt
          echo "-------- build the docs --------"
          make clean
          make html
          docroot=`mktemp -d`
          cp -r build/html/. "${docroot}/"
          cd ..
          git clean -fxd
        
          echo "-------- update gh-page --------"
          exists=`git ls-remote --heads origin "gh-pages"`
          if [[ -z ${exists} ]]; then
            echo "gh-pages not exists"
            git checkout --orphan gh-pages
          else
            echo "gh-pages exists"
            git checkout gh-pages
          fi
          git rm -rf .
          git clean -fxd
          mv "${docroot}" docs-tmps
          shopt -s dotglob nullglob
          mv docs-tmps/* .
          rm -r docs-tmps
          git config --global user.name "${GITHUB_ACTOR}"
          git config --global user.email "${GITHUB_ACTOR}@users.noreply.github.com"
          git add .
          changes=`git status --porcelain`
          if [[ -z ${changes} ]]; then
            echo "no changes"
          else
            git commit -m "update docs"
          fi
          
      - name: Push changes
        uses: ad-m/github-push-action@master
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          branch: gh-pages
